package org.jeecg.modules.sxaq.upgrade.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: jeecg-boot-parent
 * @description
 * @author: JackWong
 * @create: 2021-05-10 14:06
 **/
@Api(tags = "文件上传功能")
@RestController
@RequestMapping("/sys")
@Slf4j
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
    public static File DEST;

    @PostMapping("/file/upload")
    public Result<?> upload(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return new Result<>().error500("上传失败,请选择文件");
        }
        String fileName = file.getOriginalFilename();
        String filePath;
        if (fileName.contains("apk")){
            filePath = "/opt/sxaq-f2/web/app/files/android";
        }else {
            filePath = "/opt/sxaq-f2/web/app/files/ios/";
        }
        if (!new File(filePath).isDirectory()) {
            new File(filePath).mkdirs();
        }

        DEST = new File(filePath,fileName.split("\\.")[0]+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"."+fileName.split("\\.")[1]);
        if (DEST.exists()){
            DEST = null;
            return new Result<>().error500("文件已存在");
        }

        try {
            DEST.createNewFile();
            file.transferTo(DEST);
            LOGGER.info("上传成功");
            String dest = "https://mdm.relax.link/app"+DEST.toString().split("app")[1];
            return new Result<>().ok(dest);
        }catch (IOException e){
            LOGGER.error(e.toString(), e);
            DEST = null;

            return new Result<>().error500("APP文件上传错误");
        }
    }
}
